package com.wx.forum.utils;

import com.wx.forum.common.AppResult;
import com.wx.forum.common.ResultCode;
import com.wx.forum.contant.Contants;
import com.wx.forum.exception.ApplicationException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtil {
    private static final long JWT_EXPIRATION = 7*24*60*60*1000;//过期时间(7天)
    //密匙
    private static final String secretKey = "vYsvJXG6WUn5GVVpiB1JDj2VsjfebuOlR28S/WuTltE=";
    //⽣成安全密钥
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey));
    /**
     * 生成token
     */
    public static String getToken(Map<String,Object> claim){
        //过期时间
        Date date = new Date(System.currentTimeMillis()+JWT_EXPIRATION);
        // String secretKey = "qwertyuknbvcdrtyuikmnbvcdfjnbvcdjnbvc";//长度需要大于256bit
        // Key key = Keys.hmacShaKeyFor(secretKey.getBytes());

        //这个setClaims的参数是一个map类型
        //builder相当于建立一个令牌
        //compact相当于将前面设置的负载整合到一起(结束)

        String jwt = Jwts
                .builder()
                .setClaims(claim)//设置负载
                .setExpiration(date)//设置过期时间
                .signWith(key)
                .compact();
        return  jwt;
    }
    /**
     * 校验token
     * claims为空说明校验失败
     */
    public static Claims parseToken(String token){
       // log.info("校验的token: {}",token);
        //创建解析器, 设置签名密钥
        JwtParser builder = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            //解析token
            claims = builder.parseClaimsJws(token).getBody();
        }catch (Exception e){
           // throw new ApplicationException(AppResult.failed("用户未登录"));
        }
        return claims;
    }
    /**
     * 根据token获取id
     */
    public static Long getIdByToken(String token){
        //校验解析token
        Claims claims = parseToken(token);
        if(claims == null){
            //用户未登录
            //打印信息
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
           throw new ApplicationException(AppResult.failed(ResultCode.FAILED_FORBIDDEN));

        }
        //获取id
        //将Integer转换成Long类型
        Integer value = (Integer) claims.get(Contants.TOKEN_USER_ID);
        Long userId = Long.valueOf(value.longValue());

        return userId;
    }
    // 验证 JWT 是否过期
    public static boolean isTokenExpired(String token) {
        //创建解析器, 设置签名密钥
        JwtParser builder = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            //解析token
            claims = builder.parseClaimsJws(token).getBody();
        }catch (Exception e){
            // throw new ApplicationException(AppResult.failed("用户未登录"));
        }
        return claims.getExpiration().before(new Date());
    }

}
